package org.webapp.managedBeans;

import java.io.Serializable;
import java.util.logging.Logger;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.ejb.api.UtilisateurInterface;
import org.ejb.entities.Address;
import org.ejb.entities.Utilisateur;
import org.ejb.entities.ValidationException;
import org.primefaces.event.FlowEvent;

@ManagedBean(name="userWizard")
@SessionScoped
public class UserWizard implements Serializable  {  

	/**
	 * 
	 */
	private static final long serialVersionUID = 4199433451164908005L;

	private Utilisateur user = new Utilisateur();
	private Address address = new Address();

	private boolean skip;  

	private static Logger logger = Logger.getLogger(UserWizard.class.getName());  

	public Utilisateur getUser() {  
		return user;  
	}  

	public void setUser(Utilisateur user) {  
		this.user = user;  
	}  

	public Address getAddress() {
		return address;
	}

	public void setAddress(Address address) {
		this.address = address;
	}

	public void save(ActionEvent actionEvent) {  
		/* Persist user */ 

		UtilisateurInterface ui=null;
		InitialContext ic;
		try {
			ic = new InitialContext();	
			ui = (UtilisateurInterface)ic.lookup("org.ejb.stateless.UtilisateurStateless@Remote");
		}catch (NamingException e) {
			e.printStackTrace();
		}
		try {
			ui.createCustomer(user, address);
		}catch (ValidationException e) {
			e.printStackTrace();
		}
		catch (Exception e) {
			FacesMessage Errmsg = new FacesMessage(FacesMessage.SEVERITY_FATAL,"Erreur ", "problème interne, veuillez essayer ultérieurement");  
			FacesContext.getCurrentInstance().addMessage(null, Errmsg);
			e.printStackTrace();
			return;
		}
		/* end Persist user */
		FacesMessage msg = new FacesMessage("Compte crée avec succès ", "Bienvenue Monsieur :" + user.getFirstname());  
		FacesContext.getCurrentInstance().addMessage(null, msg);  
	}


	public boolean isSkip() {  
		return skip;  
	}  

	public void setSkip(boolean skip) {  
		this.skip = skip;  
	}  

	public String onFlowProcess(FlowEvent event) {  
		logger.info("Current wizard step:" + event.getOldStep());  
		logger.info("Next step:" + event.getNewStep());  

		if(skip) {  
			skip = false;   //reset in case user goes back  
			return "confirm";  
		}  
		else {  
			return event.getNewStep();  
		}  
	}  
} 
